package class11_tree;

import java.util.LinkedList;
import java.util.Queue;

/**
 * 二叉树的按层遍历
 */
public class Code01 {

    static class Node {
        int value;
        Node left;
        Node right;

        public Node(int value) {
            this.value = value;
        }
    }

    /**
     * 按层遍历二叉树
     *
     * @param head
     */
    public static void level(Node head) {
        // 边界判断
        if (head == null) {
            return;
        }
        // 双端队列
        Queue<Node> queue = new LinkedList<>();
        queue.add(head);
        while (!queue.isEmpty()) {
            // 弹出头节点
            Node cur = queue.poll();
            System.out.print(cur.value);
            // 左节点进入队列
            if (cur.left != null) {
                queue.add(cur.left);
            }
            // 右节点进入队列
            if (cur.right != null) {
                queue.add(cur.right);
            }
        }
    }

    public static void main(String[] args) {
        Node head = new Node(1);
        head.left = new Node(2);
        head.right = new Node(3);
        head.left.left = new Node(4);
        head.left.right = new Node(5);
        head.right.left = new Node(7);

        level(head);
    }
}
